package com.example.easypan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.easypan.common.Result;
import com.example.easypan.pojo.FileInfo;
import com.example.easypan.pojo.Share;
import com.example.easypan.service.impl.FileInfoServiceImpl;
import com.example.easypan.service.impl.ShareServiceImpl;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 功能：
 * 作者：cyan
 * 日期：2025/2/14 下午8:03
 */
@RestController
@RequestMapping("/share")
public class ShareController {
    @Resource
    private ShareServiceImpl shareService;
    @Autowired
    private FileInfoServiceImpl fileInfoServiceImpl;

    @PostMapping("/list")
    public Result getList()
    {

        List<Share> list = shareService.list();
        return Result.success(list);
    }

    @PostMapping("/add")
    public Result addShare(@RequestBody Share share, @RequestParam int day)
    {
        LocalDateTime currentTime = LocalDateTime.now();  // 获取当前时间
        LocalDateTime newTime = currentTime.plusDays(day);  // 当前时间加上指定的天数


        // 将 LocalDateTime 转换为 Date
        Date expirationTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());

        // 设置过期时间
        share.setExpirationTime(expirationTime);

        boolean flag = shareService.save(share);

        if(flag)
        {
            return Result.success("更新成功");
        }
        else
        {
            return Result.error("更新失败");
        }

    }

    @PostMapping("/find")
    public Result extractDownloadUrl(@RequestBody Share share) {
        LambdaQueryWrapper<Share> wrapper3=new LambdaQueryWrapper<>();
        wrapper3.eq(Share::getShareUrl,share.getShareUrl());
        Share queryShareFileId=shareService.getOne(wrapper3);

        int shareFileId=queryShareFileId.getFileId();

        //如果文件删除就无法获取链接
        LambdaQueryWrapper<FileInfo> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(FileInfo::getFileId,shareFileId);
        FileInfo fileInfo=fileInfoServiceImpl.getOne(wrapper1);
        if(fileInfo.getDelFlag()!=2)
        {
            return Result.error("文件已经删除");
        }

        LambdaQueryWrapper<Share> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Share::getShareUrl,share.getShareUrl())
                .eq(Share::getCode,share.getCode())
                .ge(Share::getExpirationTime,new Date());

        Share one = shareService.getOne(wrapper);

        return Result.success(one);
    }


}